package com.orangelife.mobile.pay.view;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.common.jump.PayJumper;
import com.common.util.CommonHttpBiz;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.StringUtil;
import com.curry.android.util.ToastHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.fragment.OrangeLifeBaseFragment;
import com.orangelife.mobile.pay.biz.PayPwdHttpBiz;
import com.orangelife.mobile.widget.SafetyCodeEditText;

import org.json.JSONObject;

import java.util.Map;

/**
 * <p>
 * Created by 吴格非 on 2017-1-3.
 * <p>
 *
 * @author 吴格非
 * @since v1.0.0
 */

public class PayPwdDialog extends Dialog {

    private Context context;
    private SafetyCodeEditText scetPayPwd;
    private ImageView ivClose;
    private TextView tvTitle;
    private TextView tvForget;

    /** 是否是设置密码(还有输入密码模式) */
    private boolean isSetPwdMode = true;

    /** 设置密码模式,是否第一次输入 */
    private boolean isFirstInputInSetMode = true;

    /** 第一次输入的密码,用于校验 */
    private String firstInputText;

    public PayPwdDialog(Context context, boolean isSetPwdMode) {
        super(context, R.style.NewDialogStyle);
        this.context = context;
        this.isSetPwdMode = isSetPwdMode;
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        setListener();
        setAttr();
        setTitle("");
    }

    public void setTitle(String title) {
        if (StringUtil.isBlank(title)) {
            if (isSetPwdMode) {//设置密码模式
                tvTitle.setText("请输入6位数字");
            } else {//输入密码模式
                tvTitle.setText("输入支付密码");
            }
        } else {
            tvTitle.setText(title);
        }
    }

    public void clearInput() {
        scetPayPwd.setText("");
    }

    private void initView() {
        LayoutInflater inflater = LayoutInflater.from(this.context);
        View view = inflater.inflate(R.layout.dialog_pay_pwd, null);
        setContentView(view);
        ivClose = (ImageView) findViewById(R.id.ivClose);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        tvForget = (TextView) findViewById(R.id.tvForget);
        scetPayPwd = (SafetyCodeEditText) findViewById(R.id.scetPayPwd);
        scetPayPwd.setmBorderWidth(3);
        scetPayPwd.setmBorderColor(getContext().getResources().getColor(R.color.boder_button));
        scetPayPwd.setmBorderRadius(10);
        scetPayPwd.setmPasswordLength(6);
        scetPayPwd.setmPasswordColor(getContext().getResources().getColor(R.color.text_black));
        if (isSetPwdMode) {
            tvForget.setVisibility(View.GONE);
        }
        setCanceledOnTouchOutside(false);
    }

    public void showKeyboard(){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                scetPayPwd.setFocusable(true);
                scetPayPwd.setFocusableInTouchMode(true);
                scetPayPwd.requestFocus();
                //调用系统输入法
                InputMethodManager inputManager = (InputMethodManager) scetPayPwd
                        .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(scetPayPwd, 0);
            }
        },200);

    }

    private void setListener() {
        scetPayPwd.setOnInputFinishListener(new SafetyCodeEditText.OnInputFinishListener() {
            @Override
            public void onFinish(String text) {
                if (isSetPwdMode) {
                    inputPwdInSettingMode(text);
                } else {
                    requestValidatePayPwd();
                }
            }
        });
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        tvForget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jumpToModPayPwd();
            }
        });
    }

    private void inputPwdInSettingMode(String text) {
        if (isFirstInputInSetMode) {//第一次输入密码
            isFirstInputInSetMode = false;
            firstInputText = text;
            setTitle("请确认您的支付密码");
            scetPayPwd.setText("");
        } else {
            if (text != null && !text.equals(firstInputText)) {
                ToastHelper.getInstance()._toast("两次输入不一致,请重新设置");
                isFirstInputInSetMode = true;
                firstInputText = "";
                scetPayPwd.setText("");
                setTitle("请输入6位数字");
            } else {//提交密码
                requestCommitPayPwd();
            }
        }
    }

    private PayPwdBus bus;

    public void setPayPwdBus(PayPwdBus bus) {
        this.bus = bus;
    }

    public interface PayPwdBus {
        void onEvent(int eventNum);
    }

    private OnValidatePayPwdListener onValidatePayPwdListener;

    public void setOnValidatePayPwdListener(OnValidatePayPwdListener onValidatePayPwdListener) {
        this.onValidatePayPwdListener = onValidatePayPwdListener;
    }

    public interface OnValidatePayPwdListener {
        void onValidated(String statusCode, String statusInfo);
    }

    /** 验证支付密码 */
    private void requestValidatePayPwd() {
        PayPwdHttpBiz.validatePayPwd(scetPayPwd.getText().toString(), new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                Map<String, Object> map = CommonHttpBiz.handleEntity(jsonObject);
                if (map != null) {
                    String statusCode = String.valueOf(map.get("stateCode"));
                    String statusInfo = String.valueOf(map.get("stateInfo"));
                    if (onValidatePayPwdListener != null) {
                        onValidatePayPwdListener.onValidated(statusCode, statusInfo);
                    }
                }
            }
        });
    }

    /** 提交设置的支付密码 */
    private void requestCommitPayPwd() {
        ((OrangeLifeBaseActivity) context).showDialog();
        PayPwdHttpBiz.commitPayPwd(scetPayPwd.getText().toString(), new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                dismiss();
                ((OrangeLifeBaseActivity) context).closeDialog();
                if (OrangeErrorHandler.getInstance().isSuccess(jsonObject)) {
                    ToastHelper.getInstance()._toast("设置完成");
                    if (bus != null) {
                        bus.onEvent(1);
                    }
                } else {
                    ToastHelper.getInstance()._toast("设置失败,请重试");
                }
            }
        });
    }

    private void jumpToModPayPwd() {
        PayJumper.jumpToModPwd(context, true);
    }

    private void setAttr() {
        Window dialogWindow = this.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics d = this.context.getResources().getDisplayMetrics();
        lp.width = (int) ((double) d.widthPixels * 0.8D);
        dialogWindow.setAttributes(lp);
    }
}
